<?php
/* Nerijus Terebas www.nerj.us
Web saitas kaip proxy serveris - serverine dalis
papildomai reikalingas localus python serveris
https://code.google.com/p/qroxy-app/
 */
$url=inputParam('url'); 
$method=inputParam('method'); 
$headers=inputParam('headers'); 
$postdata=inputParam('postdata'); 

//$headers_o = $headers;
foreach ($headers as $key => $value){
if ((strtolower($key) !== strtolower('Authorization')) and (strtolower($key) !== strtolower('User-Agent')) and (strtolower($key) !== strtolower('Referer')) and (strtolower($key) !== strtolower('Accept-Encoding')) and (strtolower($key) !== strtolower('Host'))) {
$headers_o[] = $key.": ".$value;
 } elseif ((strtolower($key) === strtolower('Authorization')) and (strtolower(substr($value, 0, 6)) === 'digest')) {
 $headers_o[] = $key.": ".$value;
 } elseif ((strtolower($key) === strtolower('Authorization')) and (strtolower(substr($value, 0, 5)) !== 'basic')) {
 $headers_o[] = $key.": ".$value;
 }
}
        $response_status = '500';
        $response_headers = array();
        $response_body = '';

       // logging.info("%s %s", method, url)


            $up = parse_url($url);
 if(function_exists('curl_init')) {
 //    $fp = fopen("aaaa.txt", "a+");
 // fwrite($fp, @json_encode($headers)."\n");
 // fclose($fp);
 
 $curl = curl_init(); 
  curl_setopt($curl, CURLOPT_URL, $url); 
  curl_setopt($curl, CURLOPT_HEADER, 1);
  curl_setopt($curl, CURLOPT_USERAGENT, $headers['User-Agent']); 
  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers_o); 
  curl_setopt($curl, CURLOPT_REFERER, $headers['Referer']); 
  curl_setopt($curl, CURLOPT_ENCODING, $headers['Accept-Encoding']); 
  curl_setopt($curl, CURLOPT_AUTOREFERER, 1); 
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//  curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1); 
  curl_setopt($curl, CURLOPT_TIMEOUT, 600); 
//curl_setopt($curl, CURLINFO_HEADER_OUT, true);
  if (strtolower($method) === 'post') {
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
  }
    if (strtolower(substr($headers['Authorization'], 0, 5)) === 'basic') {
  list($tmp, $pswdata) = explode(" ", $headers['Authorization'], 2);
   $pswdata =  base64_decode($pswdata);
  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
  curl_setopt($curl, CURLOPT_USERPWD,  $pswdata);
   } elseif (strtolower(substr($headers['Authorization'], 0, 6)) === 'digest') {
   curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST );
   } elseif (array_key_exists ( 'Authorization' , $headers )) {
   curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY );
   } 
   if (strtolower($up['scheme']) === 'https') {
  curl_setopt($curl0, CURLOPT_SSL_VERIFYPEER, false);
  }

//  curl_setopt ($curl0, CURLOPT_COOKIEFILE, $gacookie);
//  curl_setopt ($curl0, CURLOPT_COOKIEJAR, $gacookie);
 $ret = curl_exec($curl);
 if (empty($ret)) {
    // some kind of an error happened
	$response_headers=array(array('Content-Type','text/plain'));
    $response_body=curl_error($curl);
    curl_close($curl); // close cURL handler
} else {
    $info = curl_getinfo($curl);
	$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    curl_close($curl); // close cURL handler

    if (empty($info['http_code'])) {
	$response_headers=array(array('Content-Type','text/plain'));
    $response_body="No HTTP code was returned";
    } else {
        $response_status=$info['http_code'];
$response=$ret;

        $header = substr($response, 0, $header_size);

		$response_headers = get_headers_from_curl_response($header);
	//	var_dump($response_headers);
list($header2, $response_body) = explode("\r\n\r\n", $response, 2);

    }

}
 $data = array(
   'status' => intval($response_status),
   'headers' => $response_headers,
    'body' => base64_encode($response_body),
 );
 } else {
  $data = array(
   'status' => intval(200),
    'headers' => array(array('Content-Type','text/plain')),
    'body' => base64_encode("Not found CURL module"),
 );
 }

/*

  $data = array(
    'status' => intval(200),
   'headers' => array(array('Content-Type','text/plain')),
     'body' => base64_encode("url $url\n". "m $method\n"."h  ".@json_encode($headers)."hr  ".@json_encode($response_headers)."\n p $postdata\n"),
   'body' => base64_encode("url $url\n". "m $method\n"."h  ".@json_encode($headers)."\n"."hr  ".@json_encode($response_headers)."\n p $postdata\n"),
);

*/           
echo json_encode($data);

function inputParam($name)
{
if ($name === 'headers') {
            $headers2 = array();
foreach ($_POST as $name2 => $value2){ 
		 if (substr($name2, 0, 7)==='header-') {
                    $n = substr($name2, 7);
                    $n = cap_header_key($n);
                    $v = $value2;
                    $v =decode2($v);
                    $headers2[$n] = $v;
            
			}}return $headers2;}
        else {
            $v = $_POST['qroxy-' . $name];
            $v = decode2($v);
            return $v;
			}
}    
function decode2($value) {
return base64_decode($value);
}
function cap_header_key($key) {
$ck=explode ('-' , $key);
$ck = array_map("ucfirst", $ck);
return implode('-', $ck);
}

function get_headers_from_curl_response($headerContent)
{

    $headers5 = array();

    // Split the string on every "double" new line.
    $arrRequests = explode("\r\n\r\n", $headerContent);

    // Loop of response headers. The "count() -1" is to 
    //avoid an empty row for the extra line break before the body of the response.
    for ($index = 0; $index < count($arrRequests) -1; $index++) {

        foreach (explode("\r\n", $arrRequests[$index]) as $i => $line)
        {
            if ($i === 0) {
      //          $headers5[$index]['http_code'] = $line;
	  } 
            else
            {
                list ($key, $value) = explode(': ', $line);
				if ((strtolower($key) !== strtolower('Transfer-Encoding')) and (strtolower($key) !== strtolower('Content-Encoding')) and (strtolower($key) !== strtolower('Content-Length'))) {
                $headers5[] = array($key,$value); 
				}
            }
        }
    }

    return $headers5;
}

?>
